//
//  TXFPSLabel.swift
//  OneDay
//
//  Created by cheng xi on 2016/9/30.
//  Copyright © 2016年 xicheng. All rights reserved.
//

import UIKit

let kSize = CGSize(width: 70, height: 20)


class TXFPSLabel: UILabel {

  fileprivate var link:CADisplayLink! = nil
  fileprivate var count:Int  = 0
  
  fileprivate var lastTime:TimeInterval = 0
  
  fileprivate var _font:UIFont! = nil
  
  fileprivate var _subFont:UIFont! = nil
  
  fileprivate var interval:TimeInterval = 0
  override init(frame:CGRect) {
    var f = frame
    if (f.size.width == 0 && f.size.height == 0) {
      f.size = kSize;
    }
    super.init(frame: f)
    self.layer.cornerRadius = 5
    self.clipsToBounds = true
    self.textAlignment = NSTextAlignment.center
    self.isUserInteractionEnabled = false
    self.backgroundColor = UIColor(white: 0.0, alpha: 0.7)
    _font = UIFont(name: "Menlo", size: 14)
    _subFont = UIFont(name: "Menlo", size: 4)
    unowned let instance =  self
    link = CADisplayLink(target: instance, selector: #selector(TXFPSLabel.tick(_:)))
    link.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
  }
  
  func tick(_ link:CADisplayLink){
    if self.lastTime == 0 {
      self.lastTime = link.timestamp
      return
    }
    
    count = count + 1
    
    let delta = link.timestamp - self.lastTime
    if delta < 1 {
      return
    }
    lastTime = link.timestamp
    let fps:CGFloat = CGFloat(count) / CGFloat(delta)
    count = 0
    
    let progress = fps / 60.0
    
    let color = UIColor(hue: 0.27 * (progress - 0.2),saturation:1 ,brightness:0.9 ,alpha:1.0)
    
  
    let text = NSMutableAttributedString(string: "\(Int(round(fps)))  fps")
    text.tx_setTextColor(color)
    text.tx_setFont(_font)
//    [text setColor:color range:NSMakeRange(0, text.length - 3)];
//    [text setColor:[UIColor whiteColor] range:NSMakeRange(text.length - 3, 3)];
//    text.font = _font;
//    [text setFont:_subFont range:NSMakeRange(text.length - 4, 1)];
    
    self.attributedText = text;
    
  }
  
  override func sizeThatFits(_ size: CGSize) -> CGSize {
    return kSize
  }
  
  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

}
